package com.itbaima.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * 切面类
 */
@Aspect
@Component
public class InvokeLogAspect {

    /**
     * 确定切点
     */
    @Pointcut("@annotation(com.itbaima.aop.InvokeLog)")
    public void pt() {
    }

    /**
     * 环绕通知
     * @param pjp
     * @return
     */
    @Around("pt()")
    public Object printLog(ProceedingJoinPoint pjp) {
        // 目标方法调用前
        Object proceed = null;
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        String methodName = signature.getMethod().getName();
        System.out.println(methodName + "即将被调用！");
        try {
            proceed = pjp.proceed();
            // 目标方法调用后
            System.out.println(methodName + "调用完成！");
        } catch (Throwable e) {
            e.printStackTrace();
            // 目标方法出现异常
            System.out.println(methodName + "出现异常！");
        }
        return proceed;
    }

}
